<template>
  <div class="courier-container">
    <!-- 列表视图 -->
    <div v-if="currentView === 'list'" class="courier-list-view">
      <CourierList 
        @add-courier="showAddCourier" 
        @edit-courier="showEditCourier" 
        @view-courier="showCourierDetail" 
      />
    </div>
    
    <!-- 详情视图 -->
    <div v-else-if="currentView === 'detail'" class="courier-detail-view">
      <el-page-header 
        :icon="Back" 
        title="返回列表" 
        @back="backToList" 
        class="page-header"
      />
      <CourierDetail 
        :courier="currentCourier" 
        @edit-courier="showEditCourier" 
        @close="backToList" 
      />
    </div>
    
    <!-- 表单视图（新增或编辑） -->
    <div v-else-if="currentView === 'form'" class="courier-form-view">
      <el-page-header
        :icon="Back"
        :title="isEdit ? '返回详情' : '返回列表'"
        @back="backToPrevious"
        class="page-header"
      />
      <CourierForm 
        :courier-data="currentCourier" 
        :is-edit="isEdit" 
        @save="handleSaveCourier" 
        @cancel="backToPrevious" 
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { Back } from '@element-plus/icons-vue'
import CourierList from './components/CourierList.vue'
import CourierDetail from './components/CourierDetail.vue'
import CourierForm from './components/CourierForm.vue'
import type { Courier } from '@/api/courier'

// 视图状态: 'list' | 'detail' | 'form'
const currentView = ref<'list' | 'detail' | 'form'>('list')
const isEdit = ref(false)
const previousView = ref<'list' | 'detail' | 'form'>('list')
const currentCourier = ref<Courier | null>(null)

// 显示配送员详情
const showCourierDetail = (courier: Courier) => {
  currentCourier.value = courier
  previousView.value = currentView.value
  currentView.value = 'detail'
}

// 显示新增配送员表单
const showAddCourier = () => {
  currentCourier.value = null
  isEdit.value = false
  previousView.value = currentView.value
  currentView.value = 'form'
}

// 显示编辑配送员表单
const showEditCourier = (courier: Courier) => {
  currentCourier.value = courier
  isEdit.value = true
  previousView.value = currentView.value
  currentView.value = 'form'
}

// 返回列表
const backToList = () => {
  currentView.value = 'list'
}

// 返回前一个视图（详情或列表）
const backToPrevious = () => {
  currentView.value = previousView.value
}

// 保存配送员处理
const handleSaveCourier = (courierData: any) => {
  // 如果是编辑，返回详情页；如果是新增，返回列表页
  currentView.value = isEdit.value ? 'detail' : 'list'
  
  // 如果是编辑，更新当前配送员数据
  if (isEdit.value && currentCourier.value) {
    currentCourier.value = { ...currentCourier.value, ...courierData }
  }
}
</script>

<style scoped>
.courier-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.courier-list-view,
.courier-detail-view,
.courier-form-view {
  width: 100%;
}
</style>

